from django.shortcuts import render, redirect
from django.views.generic import CreateView, ListView, DeleteView, UpdateView, DetailView
from django.views.generic.base import TemplateView
from django.contrib.auth.models import User
#from django.contrib.auth.mixins import LoginRequiredMixin
from braces.views import LoginRequiredMixin
from django.urls import reverse_lazy
from django.http import HttpResponse, JsonResponse
from django.core.exceptions import ObjectDoesNotExist
import json

from order.models import OrderModel as Order, OrderContentModel as OrderContent
from .models import CategoryModel as Category
from .models import ProductModel as Product
from .forms import CategoryAddForm, ProductAddForm 

# Create your views here.

##BEGIN: Add by SRJ-SGL 
##分类列表
class GetCategroyProductTree:
    def getZtreeData(orderid):
        ## 生成树状结构 开始
        categorys = Category.objects.all()
        productTree = []
        for obj in  categorys:
            objNode = {}
            products = Product.objects.filter(category_id=obj.id)

            child = []
            for item in products:
                itemNode = {}
                itemNode['id'] = item.id
                itemNode['name'] = item.spec
                itemNode['parentid'] = obj.id
                if (orderid):
                    q={}
                    q['order_id'] = orderid 
                    q['productCategoryId'] = obj.id
                    q['productId'] = item.id 
                    content = OrderContent.objects.filter(**q)
                    if content.count() > 0:
                        itemNode['count'] = content.first().productCount
                        if (itemNode['count'] > 0):
                            objNode['open'] = 'true'
                child.append(itemNode)

            objNode['id'] = obj.id
            objNode['name'] = obj.name
            objNode['parentid'] = 0 
            objNode['children'] = child 
        
            productTree.append(objNode)
        return productTree
        ## 生成树状结构 结束 

class CategoryListPageView(LoginRequiredMixin, ListView):
    ## login_url = "/account/login/"  和下边一行的功能是一样的,一个是硬编码,一个是灵活实现
    login_url = reverse_lazy('user_login') 
    template_name = "product/category-list.html"

    def get(self, request):
        return render(request, self.template_name)

    def post(self, request, *args, **kwargs):
        ## 过滤条件参数
        ## 判断是搜索的数据还是直接显示的数据
        q = {}
        page = request.POST.get('page')
        rows = request.POST.get('limit')

        filter_name = request.POST.get('filter_name')         

        if filter_name:
            q['name__icontains'] = filter_name

        categorys = Category.objects.filter(**q)

        start = (int(page) - 1) * int(rows)
        end = (int(page) - 1) * int(rows) + int(rows)

        total = categorys.count()
        categorys = categorys[start:end]

        dict = []
        resultdict = {}

        for obj in categorys:
            dic = {}
            dic['id'] = obj.id
            dic['name'] = obj.name
            dic['created'] = obj.created.strftime("%Y-%m-%d %H:%M:%S")
            dict.append(dic)

        resultdict['code'] = 0
        resultdict['msg'] = ""
        resultdict['count'] = total 
        resultdict['data'] = dict

        return JsonResponse(resultdict, safe=False) 

class CategoryAddPageView(LoginRequiredMixin, CreateView):
    login_url = "/account/login/"
    template_name = "product/category-add.html"
    fields = ['name']

    ##Note1 当继承的是TemplateView时使用这个
    ##def get(self, request):
    ##    return render(request, "category/category-add.html")
    
    ##Note2 当继承的是CreateView时使用这个,功能与Note1是一样的,只是两种不同的实现方式
    queryset = Category.objects.all()

    def post(self, request, *args, **kwargs):
        formObj = CategoryAddForm(request.POST)
        resultdict = {}

        if formObj.is_valid():
            form_cd = formObj.cleaned_data 
            new_category = formObj.save(commit=False)
            new_category.save(form_cd)

            resultdict['code'] = 0
            resultdict['msg'] = ""
            return JsonResponse(resultdict, safe=False) 
            ##return redirect("category:show_categoryList")

        return self.render_to_response({"form":formObj})

class CategoryDelPageView(LoginRequiredMixin, DeleteView):
    login_url = "/account/login/"
    success_url = reverse_lazy('product:show_categoryList')

    model = Category

    def delete(self, request, *args, **kwargs):
        ##for k, v in kwargs.items():
        ##    print ('%s，%s；' , (k, v))
        super(CategoryDelPageView, self).delete(request, *args, **kwargs)
        return JsonResponse({'code':0, 'msg':''}) 

class CategoryUpdatePageView(LoginRequiredMixin, UpdateView):
    login_url = "/account/login/"
    success_url = reverse_lazy('product:show_categoryList')

    template_name = "product/category-update.html"
    template_name_suffix = '_update_form'
    fields = ['name']
    context_object_name = "category"

    model = Category

class CategoryDetailPageView(LoginRequiredMixin, ListView):
    ## login_url = "/account/login/"  和下边一行的功能是一样的,一个是硬编码,一个是灵活实现
    login_url = reverse_lazy('user_login') 
    template_name = "product/category-detail.html"

    def get(self, request, *args, **kwargs):
        return render(request, self.template_name, {"category_id": kwargs.get('pk')})

    def post(self, request, *args, **kwargs):
        ## 过滤条件参数
        ## 判断是搜索的数据还是直接显示的数据
        q = {}
        page = request.POST.get('page')
        rows = request.POST.get('limit')
        category_id = kwargs.get('pk')

        filter_name = request.POST.get('filter_name')
        filter_spec = request.POST.get('filter_spec')

        q['category_id'] = category_id

        if filter_name:
            q['name__icontains'] = filter_name
        if filter_spec:
            q['spec__icontains'] = filter_spec

        products = Product.objects.filter(**q)

        start = (int(page) - 1) * int(rows)
        end = (int(page) - 1) * int(rows) + int(rows)

        total = products.count()
        products = products[start:end]

        dict = []
        resultdict = {}

        for obj in products:
            dic = {}
            dic['id'] = obj.id
            dic['name'] = obj.name
            dic['category'] = obj.category.name
            dic['spec'] = obj.spec
            dic['total'] = obj.total
            dic['created'] = obj.created.strftime("%Y-%m-%d %H:%M:%S")
            dict.append(dic)

        resultdict['code'] = 0
        resultdict['msg'] = ""
        resultdict['count'] = total 
        resultdict['data'] = dict

        return JsonResponse(resultdict, safe=False) 

##产品列表
class ProductListPageView(LoginRequiredMixin, ListView):
    ## login_url = "/account/login/"  和下边一行的功能是一样的,一个是硬编码,一个是灵活实现
    login_url = reverse_lazy('user_login') 
    template_name = "product/product-list.html"

    def get(self, request):
        return render(request, self.template_name)

    def post(self, request, *args, **kwargs):
        ## 过滤条件参数
        ## 判断是搜索的数据还是直接显示的数据
        q = {}
        page = request.POST.get('page')
        rows = request.POST.get('limit')

        filter_name = request.POST.get('filter_name')
        filter_spec = request.POST.get('filter_spec')
        filter_category = request.POST.get('filter_category')

        if filter_name:
            q['name__icontains'] = filter_name
        if filter_spec:
            q['spec__icontains'] = filter_spec
        if filter_category:
            q['category__name__icontains'] = filter_category

        products = Product.objects.filter(**q)

        start = (int(page) - 1) * int(rows)
        end = (int(page) - 1) * int(rows) + int(rows)

        total = products.count()
        products = products[start:end]

        dict = []
        resultdict = {}

        for obj in products:
            dic = {}
            dic['id'] = obj.id
            dic['name'] = obj.name
            dic['category'] = obj.category.name
            dic['spec'] = obj.spec
            dic['total'] = obj.total
            dic['created'] = obj.created.strftime("%Y-%m-%d %H:%M:%S")
            dict.append(dic)

        resultdict['code'] = 0
        resultdict['msg'] = ""
        resultdict['count'] = total 
        resultdict['data'] = dict

        return JsonResponse(resultdict, safe=False) 

class ProductAddPageView(LoginRequiredMixin, CreateView):
    login_url = "/account/login/"
    template_name = "product/product-add.html"
    fields = ['name','spec']

    ##Note1 此处只能使用这个,因为要返回category做为下拉列表的内容 
    def get(self, request):
        categories = Category.objects.all()
        return render(request, "product/product-add.html", {"categories":categories})
    
    ##Note2 当继承的是CreateView时使用这个,功能与Note1是一样的,只是两种不同的实现方式
    queryset = Product.objects.all()

    def post(self, request, *args, **kwargs):
        formObj = ProductAddForm(request.POST)
        resultdict = {}

        if formObj.is_valid():
            form_cd = formObj.cleaned_data 
            new_product = formObj.save(commit=False)
            new_product.save(form_cd)

            resultdict['code'] = 0
            resultdict['msg'] = ""
            return JsonResponse(resultdict, safe=False) 
            ##return redirect("product:show_productList")

        return self.render_to_response({"form":formObj})

class ProductDelPageView(LoginRequiredMixin, DeleteView):
    login_url = "/account/login/"
    success_url = reverse_lazy('product:show_productList')

    model = Product

    def delete(self, request, *args, **kwargs):
        ##for k, v in kwargs.items():
        ##    print ('%s，%s；' , (k, v))
        super(ProductDelPageView, self).delete(request, *args, **kwargs)
        return JsonResponse({'code':0, 'msg':''}) 

class ProductUpdatePageView(LoginRequiredMixin, UpdateView):
    login_url = "/account/login/"
    success_url = reverse_lazy('product:show_productList')

    template_name = "product/product-update.html"
    template_name_suffix = '_update_form'
    fields = ['name','spec', 'total']
    context_object_name = "product"

    model = Product

class ProductAssociateOrder(LoginRequiredMixin, ListView):
    ## login_url = "/account/login/"  和下边一行的功能是一样的,一个是硬编码,一个是灵活实现
    login_url = reverse_lazy('user_login') 
    template_name = "product/associate-order-list.html"

    def get(self, request, *args, **kwargs):
        return render(request, self.template_name, {"product_id": kwargs.get('pk')})

    def post(self, request, *args, **kwargs):
        ## 过滤条件参数
        ## 判断是搜索的数据还是直接显示的数据
        q = {}
        page = request.POST.get('page')
        rows = request.POST.get('limit')
        start = (int(page) - 1) * int(rows)
        end = (int(page) - 1) * int(rows) + int(rows)

        product_id = kwargs.get('pk')

        product = Product.objects.get(id=product_id) 
        orderContents = OrderContent.objects.filter(productId=product_id)

        total = orderContents.count()
        orderContents = orderContents[start:end]

        dict = []
        resultdict = {}
        for orderContent in orderContents:
            dic = {}
            dic['id'] = orderContent.order.id
            dic['orderid'] = orderContent.order.orderid
            dic['customer'] = orderContent.order.customer.name
            dic['deposit'] = orderContent.order.deposit
            ##dic['price'] = orderContent.order.price
            dic['effectdays'] = orderContent.order.effectdays
            dic['balance'] = orderContent.order.balance
            dic['comment'] = orderContent.order.comment
            dic['orderdate'] = orderContent.order.orderdate.strftime("%Y-%m-%d")

            dic['product'] = product.name 
            dic['productCount'] = orderContent.productCount 
            dict.append(dic)

        resultdict['code'] = 0
        resultdict['msg'] = ""
        resultdict['count'] = total
        resultdict['data'] = dict

        return JsonResponse(resultdict, safe=False) 

class ProductAssociateCustomer(LoginRequiredMixin, ListView):
    ## login_url = "/account/login/"  和下边一行的功能是一样的,一个是硬编码,一个是灵活实现
    login_url = reverse_lazy('user_login') 
    template_name = "product/associate-customer-list.html"

    def get(self, request, *args, **kwargs):
        return render(request, self.template_name, {"product_id": kwargs.get('pk')})

    def post(self, request, *args, **kwargs):
        ## 过滤条件参数
        ## 判断是搜索的数据还是直接显示的数据
        q = {}
        page = request.POST.get('page')
        rows = request.POST.get('limit')
        start = (int(page) - 1) * int(rows)
        end = (int(page) - 1) * int(rows) + int(rows)

        product_id = kwargs.get('pk')

        orderContents = OrderContent.objects.filter(productId=product_id)

        total = orderContents.count()
        orderContents = orderContents[start:end]

        dict = []
        resultdict = {}
        for orderContent in orderContents:
            order = Order.objects.get(id=orderContent.order_id)
            dic = {}
            dic['id'] = order.customer.id
            dic['name'] = order.customer.name
            dic['contact'] = order.customer.contact
            dic['phone'] = order.customer.phone
            dic['created'] = order.customer.created.strftime("%Y-%m-%d %H:%M:%S")
            dict.append(dic)

        resultdict['code'] = 0
        resultdict['msg'] = ""
        resultdict['count'] = total
        resultdict['data'] = dict

        return JsonResponse(resultdict, safe=False) 

##END: Add by SRJ-SGL 
